package com.xhwl.centiotdata.suppliersystem.itc;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.ItcConstant;
import com.xhwl.common.exception.ApplicationException;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.utils.StringUtils;
import okhttp3.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @Author： wangyiling
 * @Description：itc会议系统 基本请求
 * @Date 2022/9/16
 */
@Service
public class GeneralItcHandler {
    private static final Logger log = LoggerFactory.getLogger(GeneralItcHandler.class);

    private String getToken(Integer projectId, Integer productId, String ipAndPort, String loginName, String password) {
        String url = ipAndPort + ItcConstant.LOGIN_URL;
        String session = null;
        try {
            Map<String, String> header = new HashMap<>();
            String base = Base64.getEncoder().encodeToString((loginName+":"+password).getBytes());
            header.put("Authorization", ("Basic " + base));
            header.put("OCS-APIREQUEST", ("true"));
            String result = HttpUtil.createGet(url)
                    .addHeaders(header)
                    .setConnectionTimeout(3000)
                    .setReadTimeout(5000)
                    .execute().body();
            session = JSON.parseObject(result).getJSONObject("ocs").getJSONObject("data").getString("apppassword");
            log.error("session获取成功：{}", session);
        } catch (Exception e) {
            log.error("获取失败：{}", projectId, e);
        }
        return session;
    }

    public JSONObject post(String api, Map<String, Object> param, Integer projectId, Integer productId, String ipAndPort, String loginName, String password) {
        String token = this.getToken(projectId, productId, ipAndPort, loginName, password);
        String result = null;
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api);
        try {
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", ("Bearer " + token));
            header.put("OCS-APIREQUEST", ("true"));
            result = HttpRequest
                    .post(pathBuffer.toString())
                    .addHeaders(header)
                    .body(JSON.toJSONString(param))
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【itc post】path:{};params:{}; request failed!", pathBuffer, JSON.toJSONString(param));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【itc post】path:{};params:{};result is null!", pathBuffer, JSON.toJSONString(param));
            throw new BusinessException();
        }

        JSONObject data = JSON.parseObject(result).getJSONObject("data");
        if (data == null) {
            log.error("【itc post】path:{};params:{};错误信息：{}!", pathBuffer, JSON.toJSONString(param),JSON.parseObject(result).getString("message"));
            throw new BusinessException(JSON.parseObject(result).getString("message"));
        }

        log.info("【itc post】path:{};params:{};result:{}", pathBuffer, JSON.toJSONString(param), result);
        return JSON.parseObject(result);
    }

    public JSONObject put(String api, Map<String, Object> param, Integer projectId, Integer productId, String ipAndPort, String loginName, String password) {
        String token = this.getToken(projectId, productId, ipAndPort, loginName, password);
        String result = "";
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api);
        try {
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", ("Bearer " + token));
            header.put("OCS-APIREQUEST", ("true"));
            result = HttpRequest
                    .put(pathBuffer.toString())
                    .addHeaders(header)
                    .body(param.toString())
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【itc put】path:{};params:{}; request failed!", pathBuffer, JSON.toJSONString(param));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【itc put】path:{};params:{};result is null!", pathBuffer, JSON.toJSONString(param));
            throw new BusinessException();
        }
        log.info("【itc put】path:{};params:{};result:{}", pathBuffer, JSON.toJSONString(param), result);
        return JSON.parseObject(result);
    }

    public JSONObject putOrg(String api, String param, Integer projectId, Integer productId, String ipAndPort, String loginName, String password) {
        String token = this.getToken(projectId, productId, ipAndPort, loginName, password);
        String result="";
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType,param);
        log.info("---itc put---------"+param);
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api);
        try {
            Request request = new Request.Builder().url(ipAndPort+api).method("PUT",body).addHeader("Authorization",("Bearer " + token))
                    .addHeader("OCS-APIREQUEST", ("true")).addHeader("Content-Type", "application/x-www-form-urlencoded").build();
            result = client.newCall(request).execute().body().string();
        } catch (HttpException | IOException e) {
            log.error("【itc put】path:{};params:{}; request failed!", pathBuffer, JSON.toJSONString(param));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【itc put】path:{};params:{};result is null!", pathBuffer, JSON.toJSONString(param));
            throw new BusinessException();
        }
        log.info("【itc put】path:{};params:{};result:{}", pathBuffer, JSON.toJSONString(param), result);
        return JSON.parseObject(result);
    }
    public JSONObject delete(String api, JSONObject param, Integer projectId, Integer productId, String ipAndPort, String loginName, String password) {
        String token = this.getToken(projectId, productId, ipAndPort, loginName, password);
        String result = null;
        if(param.get("id")!=null && StringUtils.isNotEmpty(param.get("id").toString()) ){
            api = api+"/"+param.get("id").toString();
        }
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api);
        try {
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", ("Bearer " + token));
            header.put("OCS-APIREQUEST", ("true"));
            result = HttpRequest
                    .delete(pathBuffer.toString())
                    .addHeaders(header)
                    .body(JSON.toJSONString(param))
                    .execute()
                    .body();
        } catch (HttpException e) {
            log.error("【itc delete】path:{};params:{}; request failed!", pathBuffer, JSON.toJSONString(param));
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【itc delete】path:{};params:{};result is null!", pathBuffer, JSON.toJSONString(param));
            throw new BusinessException();
        }
        log.info("【itc delete】path:{};params:{};result:{}", pathBuffer, JSON.toJSONString(param), result);
        return JSON.parseObject(result);
    }
    public String upload(String api, String imageUrl, Integer projectId, Integer productId, String ipAndPort, String loginName, String password) {
        String token = this.getToken(projectId, productId, ipAndPort, loginName, password);
        String result = null;

        if(StringUtils.isEmpty(imageUrl)){
            return "";
        }
        StringBuffer path = new StringBuffer()
                .append(ipAndPort)
                .append(api);
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);
            InputStream is = conn.getInputStream();

            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            ByteArrayOutputStream readStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[6024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                readStream.write(buffer, 0, len);
            }
            is.close();
            File imageFile = new File("1.jpg");
            FileOutputStream outStream = new FileOutputStream(imageFile);
            outStream.write(readStream.toByteArray());
            outStream.close();
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", ("Bearer " + token));
            header.put("OCS-APIREQUEST", ("true"));
            result = HttpRequest
                    .post(path.toString())
                    .addHeaders(header)
                    .form("image", imageFile)
                    .execute()
                    .body();
        } catch (HttpException | IOException e) {
            log.error("【itc upload】path:{};params:{}; request failed!", path, JSON.toJSONString(imageUrl));
            e.printStackTrace();
            return "";
            //throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【itc upload】path:{};params:{};result is null!", path, JSON.toJSONString(imageUrl));
            return "";
            //throw new BusinessException();
        }
        JSONObject data = JSON.parseObject(result).getJSONObject("data");
        if (data == null) {
            log.error("【itc upload】path:{};params:{};错误信息：{}!", path, imageUrl,JSON.parseObject(result).getString("message"));
            return "";
            //throw new BusinessException(JSON.parseObject(result).getString("message"));
        }
        log.info("【itc upload】path:{};params:{};result:{}", path, JSON.toJSONString(imageUrl), result);
        return data.getString("path");
    }
}
